package birdsong.example;

import java.io.IOException;
import java.net.UnknownHostException;

import birdsong.client.BirdsongClient;
import birdsong.comm.ClientComm;
import birdsong.comm.ClientSideMessage;

/**
 * A simple client that follows all users and echos whatever Birdsong messages it receives.
 * 
 * @author alc
 *
 */

public class EchoClient implements BirdsongClient {
	private static final String myNickname = "EchoClient";

	@Override
	public void start(ClientComm clientComm) {
		try {
			clientComm.connect("localhost", myNickname);

			while (true) {
				ClientSideMessage message = clientComm.getNextMessage();
				
				// Follow whoever connects:
				if (message.getType() == ClientSideMessage.Type.CONNECTED) {
					if (!message.getPayload().equals(myNickname)) {
						clientComm.follow(message.getPayload());
					}
				}
				
				// Echo all messages received:				
				if (message.getType() == ClientSideMessage.Type.BIRDSONG_MESSAGE) {
					if (!message.getSendersNickname().equals(myNickname)) {
						System.out.println("Echoing the following message: " + message);
						clientComm.sendBirdsongMessage(message.getSendersNickname() + " said: \"" + message.getPayload() + "\"");
					}
				}
			}
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}



